package org.colin.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.colin.model.ro.EmailRO;
import org.colin.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @Description:
 * @ClassName: MailServiceImpl
 * @Author: wujiangbo
 * @Date: 2020-01-06 18:05
 * @Version: 1.1.0
 */
@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendSimpleMail(EmailRO emailRO) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(emailRO.getTo());
        message.setSubject(emailRO.getObject());
        message.setText(emailRO.getContent());
        try {
            mailSender.send(message);
            log.info("发送给[{}]的普通邮件成功！", emailRO.getTo());
        } catch (Exception e) {
            log.error("发送普通邮件失败：{}", e);
        }
    }

    //<html><head></head><body><h3>哈哈，什么都没有</h3></body></html>
    @Override
    public void sendHtmlMail(EmailRO emailRO) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            //true 表⽰示需要创建⼀一个 multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(emailRO.getTo());
            helper.setSubject(emailRO.getObject());
            helper.setText(emailRO.getContent(), true);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("发送HTML邮件失败：{}", e);
        }
    }

    @Override
    public void sendAttachmentMail(EmailRO emailRO, String filePath) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            //true 表⽰示需要创建⼀一个 multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(emailRO.getTo());
            helper.setSubject(emailRO.getObject());
            helper.setText(emailRO.getContent(), true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);
            mailSender.send(message);
        } catch (MessagingException e) {
            log.error("发送带附件邮件失败：{}", e);
        }
    }
}